package com.example.demo.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 定时任务线程池配置类
 * 
 * @author zhang
 * @date 2024
 */
@Configuration
public class ScheduleTaskConfig implements SchedulingConfigurer {

    private static final Logger logger = LoggerFactory.getLogger(ScheduleTaskConfig.class);

    /**
     * 定时任务线程池大小
     */
    @Value("${spring.task.scheduling.pool.size:5}")
    private int poolSize;

    /**
     * 线程名前缀
     */
    @Value("${spring.task.scheduling.thread-name-prefix:scheduled-task-}")
    private String threadNamePrefix;

    /**
     * 配置定时任务线程池
     * 
     * @param taskRegistrar ScheduledTaskRegistrar
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(scheduledExecutorService());
        logger.info("定时任务线程池配置完成 - 线程池大小: {}, 线程名前缀: {}", poolSize, threadNamePrefix);
    }

    /**
     * 创建定时任务线程池
     * 
     * @return ScheduledExecutorService
     */
    @Bean("scheduledExecutorService")
    public ScheduledExecutorService scheduledExecutorService() {
        return Executors.newScheduledThreadPool(poolSize, new ThreadFactory() {
            private final AtomicInteger threadNumber = new AtomicInteger(1);

            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r, threadNamePrefix + threadNumber.getAndIncrement());
                thread.setDaemon(false);
                return thread;
            }
        });
    }
}

